// 公共方法
import { getOssKey, applegetAppleProduct, appleaddAppleProduct } from '@/api/common';
import UniShare from '@/uni_modules/uni-share/js_sdk/uni-share.js';
import userStore from '@/store/user';
import { Iap, IapTransactionState } from '@/utils/iap';
import { getAppLatestVersion } from '@/api/index.js';

/**
 * @name: 获取文件名
 * @param {*} url 链接地址
 * @return {*} 文件名
 **/
export function getFileName(url) {
  if (!url) return;
  const d_url = decodeURIComponent(url);
  const lastSlashIndex = d_url.lastIndexOf('/');
  const filename = d_url.substring(lastSlashIndex + 1);
  return filename;
}
/**
 * @name: 获取文件后缀
 * @param {*} url 链接地址
 * @return {*} 文件后缀
 **/
export function getFileExt(url) {
  if (!url) return;
  const d_url = decodeURIComponent(url);
  const lastSlashIndex = d_url.lastIndexOf('.');
  const ext = d_url.substring(lastSlashIndex + 1);
  return ext;
}
/**
 * @name: 是否为图片类型
 * @param {*} url 链接地址
 * @return {*} 布尔值
 **/
export function isImage(url) {
  if (!url) return false;
  const ext = getFileExt(url).toLowerCase();
  const bol = ['png', 'jpg', 'jpeg', 'gif', 'webp'].includes(ext);
  return bol;
}
/**
 * @name: 是否为pdf类型
 * @param {*} url 链接地址
 * @return {*} 布尔值
 **/
export function isPdf(url) {
  if (!url) return false;
  const ext = getFileExt(url).toLowerCase();
  return ext === 'pdf';
}
/**
 * @name: 预览文件
 * @param {*} url 链接地址
 **/
export function previewDocument(url) {
  if (!url) return;

  if (isImage(url)) {
    uni.previewImage({
      current: url,
      urls: [url]
    });
  } else {
    uni.showLoading({
      title: '加载中',
      mask: true
    });
    uni.downloadFile({
      url: url,
      success: (res) => {
        const filePath = res.tempFilePath;
        uni.openDocument({
          filePath: filePath,
          showMenu: true,
          complete: () => {
            uni.hideLoading();
          }
        });
      },
      fail: () => {
        uni.hideLoading();
      }
    });
  }
}
/**
 * @name: 获取阿里上传的key
 * @param {*} path 上传到阿里云的路径
 **/
let backOssKey = null;
let keyTimer = null;
export async function getAliOssKey(path) {
  const user = userStore();
  try {
    let ossPath = `mtym-app/${path}/${user.userInfo.providerId}`;

    let ossKeyObj = null;
    if (backOssKey) {
      ossKeyObj = backOssKey;
      keyTimer && clearTimeout(keyTimer);
      keyTimer = setTimeout(() => {
        backOssKey = null;
      }, 60000);
    } else {
      const ossRes = await getOssKey({
        key: ossPath
      });
      ossRes.data.host = ossRes.data.host + '/';
      ossKeyObj = ossRes.data;
      backOssKey = ossKeyObj;
    }

    return ossKeyObj;
  } catch (error) {}
}

/**
 * @name: 清空ossKey
 *
 *
 **/
export function clearOssKey() {
  backOssKey = null;
  if (keyTimer) {
    clearTimeout(keyTimer);
    keyTimer = null;
  }
}

/**
 * @name: 上传文件
 * @param {*} file 上传的文件
 * @param {*} path 上传到阿里云的路径
 **/
export async function uploadFileBase(file, path = 'upload') {
  const user = userStore();
  let now = new Date().getTime();
  let ossPath = `mtym-app/${path}/${user.userInfo.providerId}/${now}/${file?.name}`;
  try {
    const ossKeyObj = await getAliOssKey(path);

    const res = await uni.uploadFile({
      url: `${ossKeyObj.host}`,
      filePath: file.url,
      name: 'file',
      formData: {
        key: ossPath,
        ...ossKeyObj
      }
    });

    if (res.statusCode === 204) {
      return ossKeyObj.host + ossPath;
    }
  } catch (error) {}
}
/**
 * @name: 获取 UUID
 **/
export function getUuid() {
  let s = [];
  let hexDigits = '0123456789abcdef';
  for (let i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = '4';
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
  s[8] = s[13] = s[18] = s[23] = '-';
  let uuid = s.join('');
  return uuid;
}
/**
 * @name: 防抖
 **/
export function debounce(fn, delay = 1000) {
  let timer = null;
  return function () {
    timer && clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, arguments);
      clearTimeout(timer);
      timer = null;
    }, delay);
  };
}
/**
 * @name: 节流
 **/
export function throttle(fn, delay = 1000) {
  let timer = null;
  return function () {
    if (timer) return;
    timer = setTimeout(() => {
      fn.apply(this, arguments);
      clearTimeout(timer);
      timer = null;
    }, delay);
  };
}
/**
 * @name: 数字转成千分位格式
 * @param {*} num 数字
 * @return {*} 千分位字符串
 **/
export function numberWithCommas(num) {
  let number = 0;
  if (typeof num !== 'number') {
    number = Number(num);
  }

  return number.toLocaleString();
}
/**
 * @name: 将后台返回厘单位金额进行处理
 * @param {*} num 金额，单位厘
 * @param {*} index 保留小数位数
 * @param {*} toLocaleString 是否千分位格式化
 * @return {*} 金额值，单位元
 **/
export function amountTransfer(num, index = 0, toLocaleString = false) {
  if (!num) {
    return 0;
  }
  let amount = num;
  if (typeof num !== 'number') {
    amount = Number(num);
  }
  let amountStr = (amount / 1000).toFixed(index);
  if (toLocaleString) {
    return numberWithCommas(amountStr);
  } else {
    return amountStr;
  }
}
/**
 * @name: 将字符串中间4位变成*
 * @param {*} str 字符串
 * @return {*} 加密后字符串
 **/
export function replaceMiddleWithAsterisks(str) {
  const length = str.length;

  if (length <= 4) {
    return '****';
  }

  const start = Math.floor((length - 4) / 2);

  const firstPart = str.slice(0, start);
  const middlePart = '****';
  const lastPart = str.slice(start + 4);

  return firstPart + middlePart + lastPart;
}

/**
 * 支付方法
 * @params{payType} Number payType 支付方式 1.微信 2.支付宝 3.水单
 * @params{orderInfo} string 订单信息 支付宝支付需要
 * @params{url} string 水单支付链接
 */
export function initiationPayments(payType, orderInfo = '', url = '') {
  return new Promise((resolve, reject) => {
    if (payType === 3) {
      // 水单支付
      resolve();
      uni.navigateTo({
        url: url
      });
    } else {
      uni.getProvider({
        service: 'payment',
        success: (res) => {
          if (payType === 1) {
            // 微信支付
            resolve();
          } else if (payType === 2) {
            // 支付宝支付
            if (~res.provider.indexOf('alipay')) {
              uni.requestPayment({
                'provider': 'alipay',
                'orderInfo': orderInfo,
                success: () => {
                  resolve();
                },
                fail: (err) => {
                  reject(err);
                }
              });
            }
          } else if (payType === 100) {
            ipaPay(resolve, reject);
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    }
  });
}

async function ipaPay(resolve, reject) {
  try {
    const res = await applegetAppleProduct();
    uni.showLoading({
      title: '正在处理...',
      mask: true
    });
    const _iap = new Iap({
      products: [res.data.productNo]
    });
    // 初始化，获取iap支付通道
    await _iap.init();
    // 从苹果服务器获取产品列表
    const productList = await _iap.getProduct();
    const productId = productList[0].productid;

    // 从苹果服务器检查未关闭的订单，可选根据 username 过滤，和调用支付时透传的值一致
    const transactions = await _iap.restoreCompletedTransactions({
      username: productId
    });
    if (transactions?.length) {
      // 关闭未支付的订单
      await _iap.finishTransaction(transactions[0]);
    }

    // 请求苹果支付
    const payRes = await _iap.requestPayment({
      productid: productId,
      username: productId,
      manualFinishTransaction: true
    });
    // 验证成功后关闭订单
    await _iap.finishTransaction(payRes);
    await appleaddAppleProduct({ appleProductId: res.data.appleProductId });
    uni.hideLoading();
    resolve();
  } catch (error) {
    uni.hideLoading();
    reject();
  }
}

/**
 * 打开分享弹窗
 * @params{obj} 分享内容
 */
export function openAppShare(obj) {
  // #ifdef APP
  const share = new UniShare();
  share.show(
    {
      content: {
        //公共的分享参数配置  类型（type）、链接（herf）、标题（title）、summary（描述）、imageUrl（缩略图不能大于20K）
        type: 0,
        href: obj.href,
        title: obj.title,
        summary: obj.summary.substring(0, 40),
        imageUrl: obj.imageUrl || 'https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/small-share-logo.png'
      },
      menus: [
        {
          img: 'https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/share-weixin.png',
          text: '微信好友',
          share: {
            provider: 'weixin',
            scene: 'WXSceneSession'
          }
        },
        {
          img: 'https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/share-wechatmoments.png',
          text: '朋友圈',
          share: {
            provider: 'weixin',
            scene: 'WXSceneTimeline'
          }
        },
        {
          img: 'https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/share-image.png',
          text: '生成海报',
          share: 'custom'
        }
      ],
      cancelText: '取消分享'
    },
    (e) => {
      obj.success && obj.success(e);
    }
  );
  // #endif
}

/**
 * 复制对公信息
 */
export function copyCorporate() {
  uni.setClipboardData({
    data: `账户名称：易盟联合（深圳）科技有限公司
开户银行：招商银行股份有限公司深圳宝安中心区支行
银行账号：755977036210001`,
    success: () => {
      uni.showToast({
        icon: 'none',
        title: '复制成功'
      });
    }
  });
}

/**
 * 加密方法
 */
export function Base64(str) {
  const base64Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  let result = '';
  for (let i = 0; i < str.length; i += 3) {
    const a = str.charCodeAt(i);
    const b = i + 1 < str.length ? str.charCodeAt(i + 1) : 0;
    const c = i + 2 < str.length ? str.charCodeAt(i + 2) : 0;
    const a1 = a >> 2;
    const a2 = ((a & 3) << 4) | (b >> 4);
    const a3 = ((b & 15) << 2) | (c >> 6);
    const a4 = c & 63;
    result += base64Chars[a1] + base64Chars[a2] + (i + 1 < str.length ? base64Chars[a3] : '=') + (i + 2 < str.length ? base64Chars[a4] : '=');
  }
  return result;
}

export function toUtf8(str) {
  let out, i, c;
  out = '';
  const len = str.length;
  for (i = 0; i < len; i++) {
    c = str.charCodeAt(i);
    if (c >= 0x0001 && c <= 0x007f) {
      out += str.charAt(i);
    } else if (c > 0x07ff) {
      out += String.fromCharCode(0xe0 | ((c >> 12) & 0x0f));
      out += String.fromCharCode(0x80 | ((c >> 6) & 0x3f));
      out += String.fromCharCode(0x80 | ((c >> 0) & 0x3f));
    } else {
      out += String.fromCharCode(0xc0 | ((c >> 6) & 0x1f));
      out += String.fromCharCode(0x80 | ((c >> 0) & 0x3f));
    }
  }
  return out;
}
